"use strict";
const electron = require("electron");
const path = require("path");
const fs = require("fs");
const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const path__default = /* @__PURE__ */ _interopDefaultLegacy(path);
const fs__default = /* @__PURE__ */ _interopDefaultLegacy(fs);
const windowIdMap = {};
const registerWindowId = function(key, value) {
  windowIdMap[key] = value;
  console.log("registerWindowId", windowIdMap);
};
const removeWindowId = function(key) {
  delete windowIdMap[key];
  console.log("removeWindowId", windowIdMap);
};
electron.ipcMain.on("getWindowId", (event, arg) => {
  console.log("getWindowId", arg);
  console.log(windowIdMap[arg]);
  event.returnValue = windowIdMap[arg];
});
const createWindowMain = () => {
  const primaryDisplay = electron.screen.getPrimaryDisplay();
  const { width, height } = primaryDisplay.workAreaSize;
  let win;
  let windowX = 0, windowY = 0;
  let X, Y;
  let screenMove = null;
  return new Promise((resolve, rejects) => {
    return fs__default.default.readFile(path__default.default.join(__dirname, "../message.txt"), (err, str) => {
      if (err)
        rejects(err);
      else
        resolve(str);
    });
  }).then((str) => {
    let message = str.toString();
    let len = message.length;
    if (len == 0) {
      return new Promise((resolve) => {
        fs__default.default.appendFile(path__default.default.join(__dirname, "../message.txt"), "backGroundColor=#ffffff", (err) => {
          if (err)
            throw new Error(err.toString());
        });
      });
    } else {
      return message.split("=")[1];
    }
  }).then((backGroundColor2) => {
    console.log(backGroundColor2, "39");
    win = new electron.BrowserWindow({
      width: 1020,
      height: 670,
      frame: false,
      backgroundColor: backGroundColor2,
      resizable: false,
      maxHeight: 670,
      title: "\u5927\u725B\u9A6C\u97F3\u4E50",
      icon: path__default.default.join(__dirname, "../icons/favicon.ico"),
      webPreferences: {
        nodeIntegration: true,
        preload: path__default.default.join(__dirname, "../preload/index.js")
      }
    });
    electron.ipcMain.handle("to-close-or-small", (e, message) => {
      if (message === "quit") {
        win.destroy();
      } else {
        win.hide();
      }
    });
    win.webContents.toggleDevTools();
    function play() {
      return win.setThumbarButtons([
        {
          tooltip: "\u4E0A\u4E00\u9996",
          icon: electron.nativeImage.createFromPath(path__default.default.join(__dirname, "../icons/prev.png")),
          click() {
            win.webContents.send("main-prev");
          }
        },
        {
          tooltip: "\u6682\u505C",
          icon: electron.nativeImage.createFromPath(path__default.default.join(__dirname, "../icons/stop.png")),
          click() {
            stop();
            win.webContents.send("main-play");
          }
        },
        {
          tooltip: "\u4E0B\u4E00\u9996",
          icon: electron.nativeImage.createFromPath(path__default.default.join(__dirname, "../icons/next.png")),
          click() {
            win.webContents.send("main-next");
          }
        }
      ]);
    }
    function stop() {
      win.setThumbarButtons([
        {
          tooltip: "\u4E0A\u4E00\u9996",
          icon: electron.nativeImage.createFromPath(path__default.default.join(__dirname, "../icons/prev.png")),
          click() {
            win.webContents.send("main-prev");
          }
        },
        {
          tooltip: "\u64AD\u653E",
          icon: electron.nativeImage.createFromPath(path__default.default.join(__dirname, "../icons/play.png")),
          click() {
            play();
            win.webContents.send("main-play");
          }
        },
        {
          tooltip: "\u4E0B\u4E00\u9996",
          icon: electron.nativeImage.createFromPath(path__default.default.join(__dirname, "../icons/next.png")),
          click() {
            win.webContents.send("main-next");
          }
        }
      ]);
    }
    stop();
    electron.ipcMain.on("render-play", () => {
      play();
    });
    electron.ipcMain.on("render-play-fail", () => {
      stop();
    });
    win.setThumbnailClip({ x: 10, y: 0, width: 150, height: 60 });
    win.setThumbnailToolTip("\u5927\u725B\u9A6C\u97F3\u4E50");
    electron.ipcMain.on("change-play-thum", (e, message) => {
      console.log(message);
      win.setThumbnailToolTip(message);
      win.setTitle(message);
    });
    electron.ipcMain.on("to-close", () => {
      win.close();
    });
    electron.ipcMain.on("to-small", () => {
      win.minimize();
    });
    electron.ipcMain.on("to-middle", () => {
      win.setContentBounds({ x: windowX, y: windowY, width: 1020, height: 670 });
      win.setBounds({ x: windowX, y: windowY, width: 1020, height: 670 });
    });
    electron.ipcMain.on("to-big", () => {
      windowX = win.getBounds().x;
      windowY = win.getBounds().y;
      win.setContentBounds({ x: 0, y: 0, width, height });
      win.setBounds({ x: 0, y: 0, width, height });
    });
    electron.ipcMain.on("move-screen", (e, obj) => {
      let { mouseX, mouseY } = obj;
      let { x, y } = win.getBounds();
      screenMove = setInterval(() => {
        X = electron.screen.getCursorScreenPoint().x;
        Y = electron.screen.getCursorScreenPoint().y;
        win.setPosition(x + (X - (mouseX + x)), y + (Y - (mouseY + y)));
      }, 10);
    });
    electron.ipcMain.on("cancel-screen", () => {
      clearInterval(screenMove);
      screenMove = null;
    });
    win.on("close", (e) => {
      e.preventDefault();
      let giveWayToMain = (event, message) => {
        electron.ipcMain.removeListener("give-way-to-main", giveWayToMain);
        if (message === "quit") {
          win.destroy();
        } else if (message === "leave") {
          win.hide();
        } else {
          event.reply("main-back-way-to-render", { ifToClose: true });
        }
      };
      win.webContents.send("check-up-quit-way");
      electron.ipcMain.on("give-way-to-main", giveWayToMain);
    });
    electron.ipcMain.on("new-window", (e, message) => {
      e.preventDefault();
      electron.shell.openExternal(message);
    });
    electron.ipcMain.on("bkColor", (e, bkColor) => {
      try {
        new Promise((resolve, reject) => {
          return fs__default.default.readFile(path__default.default.join(__dirname, "../message.txt"), (err, str) => {
            if (err)
              reject(err);
            else
              resolve(str.toString());
          });
        }).then((message) => {
          let arr = message.split("=");
          arr[1] = bkColor;
          let t = "";
          arr.forEach((ele, index) => {
            t += ele;
            if (index % 2 == 0) {
              t += "=";
            }
          });
          console.log(t);
          fs__default.default.writeFile(path__default.default.join(__dirname, "../message.txt"), t, (err) => {
            if (err)
              throw new Error(err.toSting());
          });
        });
      } catch (error) {
        console.log(error);
      }
    });
    if (electron.app.isPackaged) {
      win.loadFile(path__default.default.join(__dirname, "../", "../index.html"));
    } else {
      const url = `http://${process.env["VITE_DEV_SERVER_HOST"]}:${process.env["VITE_DEV_SERVER_PORT"]}`;
      win.loadURL(url);
    }
    win.webContents.on("did-finish-load", () => {
      registerWindowId("Main", win.webContents.id);
    });
    win.webContents.on("destroyed", () => {
      removeWindowId("Main");
    });
    electron.globalShortcut.register("Ctrl+Alt+Left", () => {
      win.webContents.send("main-prev");
    });
    electron.globalShortcut.register("Ctrl+Alt+P", () => {
      win.webContents.send("main-play");
    });
    electron.globalShortcut.register("Ctrl+Alt+Right", () => {
      win.webContents.send("main-next");
    });
    return win;
  });
};
const childWindw = () => {
  const child = new electron.BrowserWindow({
    frame: false,
    transparent: true,
    backgroundColor: "#00000000",
    hasShadow: false,
    minWidth: 616,
    minHeight: 123,
    width: 616,
    height: 123,
    maxHeight: 291,
    show: false,
    skipTaskbar: true,
    webPreferences: {
      nodeIntegration: true,
      preload: path__default.default.join(__dirname, "../preload/index.js")
    }
  });
  child.webContents.toggleDevTools();
  child.webContents.on("did-finish-load", () => {
    registerWindowId("Ci", child.webContents.id);
  });
  child.webContents.on("destroyed", () => {
    removeWindowId("Ci");
  });
  child.loadURL(`http://${process.env["VITE_DEV_SERVER_HOST"]}:${process.env["VITE_DEV_SERVER_PORT"]}/#/lyric`);
  function SendXY() {
    child.webContents.send("lyric-x-y", { x: child.getSize()[0], y: child.getSize()[1] });
  }
  child.on("resize", SendXY);
  electron.ipcMain.on("get-child-x-y", (event) => {
    event.returnValue = { x: child.getSize()[0], y: child.getSize()[1] };
  });
  let X, Y;
  let screenMove;
  electron.ipcMain.on("move-child", (e, obj) => {
    let { mouseX, mouseY } = obj;
    let { x, y } = child.getBounds();
    console.log(x, y);
    screenMove = setInterval(() => {
      X = electron.screen.getCursorScreenPoint().x;
      Y = electron.screen.getCursorScreenPoint().y;
      child.setPosition(x + (X - (mouseX + x)), y + (Y - (mouseY + y)));
    }, 10);
  });
  electron.ipcMain.on("destory-move-child", () => {
    clearInterval(screenMove);
    screenMove = null;
  });
  electron.ipcMain.on("open-lyric", (e, flag) => {
    child.setAlwaysOnTop(true, "pop-up-menu");
    if (flag == true) {
      child.show();
    } else {
      child.hide();
    }
  });
  electron.ipcMain.on("no-resizable", () => {
    child.setResizable(false);
  });
  electron.ipcMain.on("can-resizable", () => {
    child.setResizable(true);
  });
  electron.ipcMain.on("mouse-can", () => {
    child.setIgnoreMouseEvents(false);
  });
  electron.ipcMain.on("mouse-no", () => {
    child.setIgnoreMouseEvents(true, { forward: true });
  });
  return child;
};
const devtool = () => {
  if (!electron.app.isPackaged && !process.env.IS_TEST) {
    try {
      const { session } = require("electron");
      const path2 = require("path");
      session.defaultSession.loadExtension(
        path2.resolve(__dirname, "../devTool")
      );
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
};
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
fs__default.default.appendFile(path__default.default.join(__dirname, "../message.txt"), "", (err) => {
  console.log(err);
});
electron.app.whenReady().then(async () => {
  let winMain = await createWindowMain();
  devtool();
  electron.app.on("activate", () => {
    if (electron.BrowserWindow.getAllWindows().length === 0) {
      createWindowMain();
    }
  });
  let appIcon = new electron.Tray(path__default.default.join(__dirname, "../icons/favicon.ico"));
  appIcon.on("double-click", () => {
    winMain.show();
  });
  const contextMenu = electron.Menu.buildFromTemplate([
    {
      label: "\u9000\u51FA",
      type: "normal",
      click: () => {
        winMain.destroy();
      }
    },
    {
      label: "\u663E\u793A\u4E3B\u9875\u9762",
      type: "normal",
      click: () => {
        winMain.show();
      }
    }
  ]);
  appIcon.setContextMenu(contextMenu);
  electron.ipcMain.on("show-context-menu", (event) => {
    const menu = electron.Menu.buildFromTemplate([
      {
        label: "\u5237\u65B0",
        type: "normal",
        role: "reload"
      },
      {
        label: "\u5F00\u53D1\u8005\u5DE5\u5177",
        type: "normal",
        role: "toggleDevTools"
      }
    ]);
    menu.popup();
  });
  electron.Menu.setApplicationMenu(null);
  electron.ipcMain.on("get-screen-X-Y", (e) => {
    e.reply("there-X-Y", { width: winMain.getBounds().width, height: winMain.getBounds().height });
  });
  let child = childWindw();
  winMain.on("closed", () => {
    child.destroy();
  });
});
electron.app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    electron.app.quit();
  }
});
